package javabasics.concurrent.threadpool;

/**
 * @Author suxiaoxiao
 * @Date 2019/6/16 17:30
 * @Version 1.0
 */
public class PThread extends Thread {

    /**
     * 线程池
     */
    private ThreadPool pool;

    /**
     * 任务
     */
    private Runnable target;

    /**
     * 是否关闭
     */
    private boolean isShuDown = false;
    private boolean isIdle = false;

    public PThread(Runnable target, String name, ThreadPool pool) {
        super(name);
        this.pool = pool;
        this.target = target;
    }

    public Runnable getTarget() {
        return target;
    }

    /**
     * 该线程是否闲置
     * @return
     */
    public boolean isIdle() {
        return isIdle;
    }

    @Override
    public void run() {
        // 只要没关闭，就一直执行
        while (!isShuDown) {
            isIdle = false;
            if (target != null) {
                // 运行任务
                target.run();
            }
            // 任务结束，到闲置状态。
            isIdle = true;
            try {
                // 任务执行完毕后，不关闭线程，而是放入线程池空闲队列。
                pool.repool(this);
                synchronized (this) {
                    // 线程空闲，等待新的任务到来
                    wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            isIdle = false;
        }
    }

    public synchronized void setTarget(Runnable newTarget) {
        target = newTarget;
        // 设置了任务之后，通知run方法，开始执行这个任务
        notifyAll();
    }

    /**
     * 关闭线程
     */
    public synchronized void shutDown() {
        isShuDown = true;
        notifyAll();
    }

}
